package com.example.teachmvandroidchart.ui

import android.annotation.SuppressLint
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import com.android.frame.mvp.CommonBaseActivity
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.example.databasetest.MyDatabaseHelper
import com.example.teachmvandroidchart.databinding.ActivityHistogramBinding
import com.example.teachmvandroidchart.databinding.ActivityHistorydataBinding
import com.example.teachmvandroidchart.databinding.ActivityMpandroidchartBinding
import com.example.teachmvandroidchart.util.DateUtil
import com.example.teachmvandroidchart.util.PickerViewUtil
import com.example.teachmvandroidchart.widget.DynamicLineChartManager
import com.gyf.immersionbar.ImmersionBar
import java.util.*

/**
 * Created by dell on 2021/8/11.
 */
class HistotyActivity: CommonBaseActivity<ActivityHistorydataBinding>() {
    private var dynamicLineChartManager1: DynamicLineChartManager? = null

    private val names: MutableList<String> = ArrayList() //折线名字集合
    private var dbHelper: MyDatabaseHelper? = null
    private val colour: MutableList<Int> = ArrayList() //折线颜色集合
    private val list: MutableList<Float> = ArrayList() //数据集合
    private var endData: String? = null
    private var startData: String? = null
    private var EndTime = false
    private var StartTime = false

    override fun handleView(savedInstanceState: Bundle?) {
        intView()

    }
    private fun intView() {
        //折线名字
        names.add("温度")
        names.add("湿度")

        //折线颜色
        colour.add(Color.CYAN)
        colour.add(Color.GREEN)


        dynamicLineChartManager1 = DynamicLineChartManager(binding.dynamicChart1, names, colour)
        dynamicLineChartManager1!!.setHightLimitLine(50F,"温度警告",Color.RED);
        dynamicLineChartManager1!!.setYAxis(100f, 0f, 10)
        dbHelper = MyDatabaseHelper(this, "temperature.db", null, 1)
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
    }
    override fun initListener() {
        //开始时间选择
        binding.startText.setOnClickListener {
            val startTime = "1990-01-01 00:00:00"
            val endTime = "2100-01-01 12:00:00"
            val formatStr = DateUtil.Y_M_D_H_M_S
            val type = booleanArrayOf(true, true, true, true, true, true)
            val currentTime = DateUtil.convertOtherFormat(DateUtil.getCurrentDateTime(), DateUtil.Y_M_D, DateUtil.Y_M_D_H_M_S)
            PickerViewUtil.selectDateTime(
                this, { date: Date?, v1: View? ->
                    startData = DateUtil.dateToString(date, "yyyy-MM-ddHH:mm:ss")
                    val sb: StringBuilder = StringBuilder(startData)
                    Log.d("字符串：", "" + sb.toString() + " 字符长度：" + sb.length)
                    val string =sb.toString().substring(0, 10)
                    startData = string
                    Log.d("字符串：", "" + startData)
                    binding.startText.text = DateUtil.date2String(date!!, formatStr)
                    binding.time.text = "等待中...."
                    StartTime = true;
                    Handler(Looper.getMainLooper()).postDelayed({
                        /**
                         * 数据初始化（200毫秒）AddDeviceActivity
                         * */
                        if (StartTime&&EndTime){
                            findHistoryData()
                        }
                    }, 300)
                }, currentTime, startTime, endTime, formatStr,
                "选择日期时间", "取消", "确定", type
            )
            //accessUrlRxJava(UrlConstant.ONE_NET_URL)
        }
        //结束时间选择
        binding.endText.setOnClickListener {
            val startTime = "1990-01-01 00:00:00"
            var endTime = "2100-01-01 12:00:00"
            val formatStr = DateUtil.Y_M_D_H_M_S
            val type = booleanArrayOf(true, true, true, true, true, true)
            val currentsTime = DateUtil.convertOtherFormat(DateUtil.getCurrentDateTime(), DateUtil.Y_M_D, DateUtil.Y_M_D_H_M_S)
            PickerViewUtil.selectDateTime(
                this, OnTimeSelectListener { date: Date?, v1: View? ->
                    endData = DateUtil.dateToString(date, "yyyy-MM-ddHH:mm:ss")
                    val sb: StringBuilder = StringBuilder(endData)
                    Log.d("字符串：", "" + sb.toString() + " 字符长度：" + sb.length)
                    val string = sb.substring(0, 10)
                    endData = string.toString()
                    Log.d("字符串：", "" + endData)
                    binding.endText.text = DateUtil.date2String(date!!, formatStr)
                    binding.time.text = "等待中...."
                    EndTime = true;
                    Handler(Looper.getMainLooper()).postDelayed({
                        /**
                         * 数据初始化（200毫秒）AddDeviceActivity
                         * */
                        if (StartTime&&EndTime){
                            findHistoryData()
                        }
                    }, 300)

                }, currentsTime, startTime, endTime, formatStr,
                "选择日期时间", "取消", "确定", type
            )

            //accessUrlRxJava(UrlConstant.ONE_NET_URL)
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }
    @SuppressLint("Range")
    private fun findHistoryData(){

        val db: SQLiteDatabase = dbHelper!!.writableDatabase
        val sql : String = "select * from `temp` where `Date` Between '$startData' and '$endData';"
        val cursor: Cursor = db.rawQuery(sql,null)
        if (cursor.moveToFirst()) {
            do {
                val Datas: String = cursor.getString(
                    cursor.getColumnIndex("Date")
                )
                val times: String = cursor.getString(
                    cursor.getColumnIndex("time")
                )
                val temp: Float = cursor.getFloat(
                    cursor.getColumnIndex("temperatures")
                )
                val hum: Float = cursor.getFloat(
                    cursor.getColumnIndex("hum")
                )
                list.add(temp.toFloat())
                list.add(hum.toFloat())
                dynamicLineChartManager1!!.HistoryAddEntry(list)
                list.clear()
            } while (cursor.moveToNext())
        }
        cursor.close()
        Handler(Looper.getMainLooper()).postDelayed({
            /**
             * 数据初始化（200毫秒）AddDeviceActivity
             * */
            binding.time.text = "数据加载完成!"
        }, 200)
    }


}
